﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Framework.Core;
using FantastPlatform.Community.IMode;
using FantastPlatform.Community.IService;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Model;
using System.Web.Script.Serialization;
using FantastPlatform.Community.Model;
using FantastPlatform.Framework.IModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace FantastPlatform.Community.UI.Service
{
    public partial class HousePersonAddService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            IHouseDistrictService HdService = ServiceFactory.CreateService<IHouseDistrictService>();
            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true };
            group.Conditions.Add(enableCondition);
            IHouseHoldService houseHoldService = ServiceFactory.CreateService<IHouseHoldService>(); ;
            IHouseHold houseHold;
            IHouseDistrict housedistrict = new FantastPlatform.Community.Model.HouseDistrict();
            IList<Sort> sorts = new List<Sort>();
            IPersonService personService = ServiceFactory.CreateService<IPersonService>();
            switch (Action)
            {
                case "GetPurposeByHouseId":
                    houseHold = houseHoldService.Get(Id);
                    string purpose = string.Join(",", (from p in houseHold.Purposes
                                                       where p.Enable = true
                                                       select p.Id.ToString()).ToArray<string>());
                    ReturnSuccessMessage(purpose);
                    break;
                case "Add":
                    int houseDistrictId = 0;
                    if (!string.IsNullOrEmpty(Request["HouseDistrict"]))
                    {
                        houseDistrictId = Int32.Parse(Request["HouseDistrict"]);
                    }

                    houseHold = JsonToEntity<HouseHold>(Data);
                    houseHold.HouseDistrict = new HouseDistrict();
                    houseHold.HouseDistrict.Id = houseDistrictId;
                    int count = 0;
                    group.Conditions.Add(new Condition { Field = "HouseDistrict.Id", Type = typeof(Int32).FullName, Value1 = houseDistrictId, Relation = Relations.And });
                    housedistrict = HdService.Get(houseDistrictId);
                    houseHold.Code = housedistrict.Code.Substring(0, housedistrict.Code.Length - 6) + (count + 1).ToString("D6");
                    houseHold.Enable = true;                    
                    GetPurpose(houseHold);
                    if (houseHold.Id == 0)
                    {
                        houseHoldService.Create(houseHold);
                    }
                    else
                    {
                        IHouseHold oldHouseHold = houseHoldService.Get(houseHold.Id);
                        houseHold.Persons = oldHouseHold.Persons;
                        houseHoldService.Update(houseHold);
                    }
                    ReturnSuccessMessage("保存住户信息成功！");

                    break;

                case "Delete":
                    List<int> ids = new List<int>();
                    string[] idArray = Data.Split(',');
                    foreach (string id in idArray)
                    {
                        ids.Add(int.Parse(id));
                    }
                    houseHoldService.Delete(ids);
                    ReturnSuccessMessage("移除记录成功");
                    break;

                case "DeletePerson":
                    ids = new List<int>();
                    idArray = Data.Split(',');
                    foreach (string id in idArray)
                    {
                        ids.Add(int.Parse(id));
                    }
                    personService.Delete(ids);
                    ReturnSuccessMessage("移除记录成功");
                    break;

                case "Get":
                    houseHold = houseHoldService.Get(Id);
                    object obj = new
                    {
                        Id = houseHold.Id,
                        Number = houseHold.Number,
                        CreateDate = houseHold.CreateDate,
                        Enbale = houseHold.Enable,
                        Description = houseHold.Description,
                        HouseDistrict = houseHold.HouseDistrict == null ? 0 : houseHold.HouseDistrict.Id,
                        CreatePoliceManNumber = houseHold.HouseDistrict.PoliceMan.Code,
                        Deadline = houseHold.Deadline
                    };
                    string jsonStr = JsonConvert.SerializeObject(obj, Formatting.Indented, new JavaScriptDateTimeConverter());
                    jsonStr = "{ 'success': 'true', 'data': " + jsonStr + "}";

                    Response.Write(jsonStr);
                    Response.End();
                    break;
                case "SearchPrompt":
                    int totalCount = 0;
                    houseHoldService = ServiceFactory.CreateService<IHouseHoldService>();
                    group = new ConditionGroup();                   
                    group.Conditions.Add(new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true });
                    if (LoginEmployee != null)
                    {
                        group.Conditions.Add(new Condition() { Field = "HouseDistrict.PoliceMan.Id", Type = typeof(int).FullName, Value1 = LoginEmployee.Id });
                    }
                    else
                    {
                        ReturnErrorMessage("");
                    }
                    group.Conditions.Add(new Condition() { Field = "Deadline", Type = typeof(DateTime).FullName, Value1 = DateTime.Now.AddDays(7), Comparison = Comparisons.Lt });
                    IList<IHouseHold> list = houseHoldService.Search(group, null, PageSize, SelfPage, out totalCount);
                    // IList<IHouseDistrict> list1 = HdService.Search(group, null, PageSize, SelfPage, out totalCount1);
                    object[] personObjList = (from o in list
                                              where o.Enable == true
                                              select new
                                              {
                                                  Name = o.Name,
                                                  Number = o.Number,
                                                  Description = o.Description,
                                                  Id = o.Id,
                                                  Owner = (from w in o.Persons
                                                           where w.PersonType != null && w.Enable == true && w.PersonType.Name == "房主"
                                                           select w.Name).FirstOrDefault(),
                                                  Leader = (from p in o.Persons
                                                            where p.PersonType != null && p.Enable == true && p.PersonType.Name == "承租人"
                                                            select p.Name).FirstOrDefault(),
                                                  CreateDate = o.CreateDate.ToString(),
                                                  ModifyDate = o.ModifyDate.ToString(),
                                                  HouseDistrict = o.HouseDistrict == null ? "" : o.HouseDistrict.Street.Name + o.HouseDistrict.Name,
                                                  Enable = o.Enable,
                                                  Purpose = string.Join(",", (from p in o.Purposes
                                                                              where p.Enable = true
                                                                              select p.Name).ToArray<string>())
                                              }).ToArray();
                    ReturnList(totalCount, personObjList);
                    break;
                case "Search":
                    int totalCount1 = 0;
                    if (LoginEmployee != null)
                    {
                        IOrganization org = (from o in LoginEmployee.EmployeePosts
                                             where o.Enable = true
                                             select o.Post.Organization).FirstOrDefault();
                        if (LoginEmployee.User != null)
                        {
                            IList<IRole> roleList2 = LoginEmployee.User.Roles;
                            List<string> roles2 = new List<string>();
                            foreach (IRole role in roleList2)
                            {
                                roles2.Add(role.Name);
                            }
                            if (roles2.Contains("社区一级管理员") || roles2.Contains("管理员"))
                            {
                            }
                            else if (roles2.Contains("社区二级管理员"))
                            {
                                group.Conditions.Add(new Condition() { Field = "HouseDistrict.PoliceMan.EmployeePosts.Post.Organization.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = org.Id });
                            }
                            else
                            {
                                group.Conditions.Add(new Condition() { Field = "HouseDistrict.PoliceMan.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = LoginEmployee.Id });
                            }
                        }
                    }
                    list = houseHoldService.Search(group, null, PageSize, SelfPage, out totalCount1);
                    // IList<IHouseDistrict> list1 = HdService.Search(group, null, PageSize, SelfPage, out totalCount1);
                    personObjList = (from o in list
                                              where o.Enable == true
                                              select new
                                              {
                                                  Name = o.Name,
                                                  Number = o.Number,
                                                  Description = o.Description,
                                                  Id = o.Id,
                                                  Owner = (from w in o.Persons
                                                           where w.PersonType != null && w.Enable == true && w.PersonType.Name == "房主"
                                                           select w.Name).FirstOrDefault(),
                                                  Leader = (from p in o.Persons
                                                            where p.PersonType != null && p.Enable == true && p.PersonType.Name == "承租人"
                                                            select p.Name).FirstOrDefault(),
                                                  CreateDate = o.CreateDate.ToString(),
                                                  ModifyDate = o.ModifyDate.ToString(),
                                                  HouseDistrict = o.HouseDistrict == null ? "" : o.HouseDistrict.Street.Name + o.HouseDistrict.Name,
                                                  Enable = o.Enable,
                                                  Purpose = string.Join(",", (from p in o.Purposes
                                                                              where p.Enable = true
                                                                              select p.Name).ToArray<string>())
                                              }).ToArray();
                    ReturnList(totalCount1, personObjList);
                    break;
                case "SearchHistory":
                    int totalCount3 = 0;
                    IList<IHouseHold> hislist = houseHoldService.LoadLisDeleted(null, PageSize, SelfPage, out totalCount3);
                    object[] personhisList = (from o in hislist
                                              where o.Enable == true
                                              select new
                                              {
                                                  Name = o.Name,
                                                  Number = o.Number,
                                                  Description = o.Description,
                                                  Id = o.Id,
                                                  Owner = (from w in o.Persons
                                                           where w.PersonType != null && w.PersonType.Name == "房主"
                                                           select w.Name).FirstOrDefault(),
                                                  Leader = (from p in o.Persons
                                                            where p.PersonType != null && p.PersonType.Name == "承租人"
                                                            select p.Name).FirstOrDefault(),
                                                  CreateDate = o.CreateDate.ToString(),
                                                  ModifyDate = o.ModifyDate.ToString(),
                                                  HouseDistrict = o.HouseDistrict == null ? "" : o.HouseDistrict.Street.Name + o.HouseDistrict.Name,
                                                  Enable = o.Enable,
                                                  Purpose = string.Join(",", (from p in o.Purposes
                                                                              where p.Enable = true
                                                                              select p.Name).ToArray<string>())
                                              }).ToArray();
                    ReturnList(totalCount3, personhisList);

                    break;
                case "SearchByCondition":

                    string Searchjson = RepairString(Data);
                    housedistrict = JsonToEntity<FantastPlatform.Community.Model.HouseDistrict>(Searchjson);
                    object[] housedistrictList = houseHoldService.SearchByCondition(housedistrict.Name);
                    ReturnList(housedistrictList.Length, housedistrictList);
                    break;
                case "GetPurPose":
                     totalCount = 0;
                    IPurposeService purposeService = ServiceFactory.CreateService<IPurposeService>();
                    IList<IPurpose> purposeList = purposeService.LoadList(null, Int32.MaxValue, 1, out totalCount);
                    object[] objList = (from o in purposeList
                                        select new
                                        {
                                            Id = o.Id,
                                            Name = o.Name,
                                            Code = o.Code,
                                            CreateDate = o.CreateDate,
                                            Enable = o.Enable
                                        }
                                           ).ToArray();
                    ReturnList(totalCount, objList);
                    break;
                case "GetHouseDistrict":
                    int DistrictCount = 0;
                    List<string> roles = new List<string>();
                    IList<IRole> roleList = LoginEmployee.User.Roles;
                    foreach (IRole role in roleList)
                    {
                        roles.Add(role.Name);
                    }
                    if (roles.Contains("管理员") || roles.Contains("社区一级管理员"))
                    {
                        Condition DistrictCondition = new Condition() { Type = typeof(int).FullName, Field = "PoliceMan.Id", Value1 = LoginEmployee.Id };
                        group.Conditions.Add(DistrictCondition);
                    }
                    else if (roles.Contains("社区二级管理员"))
                    {
                        group.Conditions.Add(new Condition()
                        {
                            Type = typeof(int).FullName,
                            Field = "Station.Id",
                            Value1 = (from p in LoginEmployee.EmployeePosts
                                      where p.Post.Organization.Name.EndsWith("派出所") && p.Enable == true
                                      select
                                           p.Post.Organization.Id
                                ).FirstOrDefault()
                        });
                    }
                    else
                    {
                        group.Conditions.Add(new Condition()
                        {
                            Type = typeof(int).FullName,
                            Field = "ResponsibilityArea.Id",
                            Value1 = (from p in LoginEmployee.EmployeePosts
                                      where p.Post.Organization.Name.EndsWith("责任区") && p.Enable == true
                                      select
                                           p.Post.Organization.Id
                                ).FirstOrDefault()
                        });
                    }
                    IList<IHouseDistrict> DistrictList = HdService.Search(group, sorts, PageSize, SelfPage, out DistrictCount);
                    var objDistrictList = (from o in DistrictList
                                           select new
                                           {
                                               Id = o.Id,
                                               Name = o.Name
                                           }
                                           ).ToArray();
                    ReturnList(DistrictCount, objDistrictList);
                    break;
                case "GetPurposeByHouseHoldId":
                    houseHoldService = ServiceFactory.CreateService<IHouseHoldService>();
                    houseHold = houseHoldService.Get(Id);
                    string purposeStr = string.Join(",", (from p in houseHold.Purposes
                                                          where p.Enable = true
                                                          select p.Id.ToString()).ToArray<string>());
                    ReturnSuccessMessage(purposeStr);
                    break;
            }
        }
        private void GetPurpose(IHouseHold business)
        {
            string[] ptIds;

            if (!string.IsNullOrEmpty(Request["PurPose"]))
            {
                ptIds = Request["Purpose"].Split(',');

                if (ptIds.Length > 0)
                {
                    business.Purposes = new List<IPurpose>();
                    foreach (string id in ptIds)
                    {
                        business.Purposes.Add(new Purpose() { Id = Int32.Parse(id) });

                    }
                }
            }

        }

        private IMode.IPerson GetOwner(HousePerson bp)
        {
            IMode.IPerson person = new FantastPlatform.Community.Model.Person();
            person.Id = bp.Id;
            person.IdCard = bp.IdCard;
            person.Name = bp.Name;
            person.Nation = bp.Nation;
            person.NativePlace = bp.NativePlace;
            person.Phone = bp.Phone;
            person.QQ = bp.QQ;
            person.RegisterAddress = bp.RegisterPlace;
            person.Sex = bp.Sex;
            person.Address = bp.Address;
            person.Description = bp.Address;
            return person;
        }

        private void GetBusinessPersons(IHouseHold houseHold)
        {
            string Data1 = "";
            if (!string.IsNullOrEmpty(Request["data1"]))
            {
                Data1 = Request["data1"];
            }
            houseHold.Persons = JsonToEntity<List<FantastPlatform.Community.IMode.IPerson>>(RepairString(Data1));
        }
        public class HousePersons
        {
            public List<HousePerson> Persons { get; set; }
        }

        public class HousePerson
        {
            //public int WorkScheduleId { get; set; }
            public int Id { get; set; }
            public string QQ { get; set; }
            public string Phone { get; set; }
            public string Address { get; set; }
            public string Nation { get; set; }
            public string NativePlace { get; set; }
            public string RegisterPlace { get; set; }
            public string PersonType { get; set; }
            public string Sex { get; set; }
            public string Name { get; set; }
            public string IdCard { get; set; }
            public string Description { get; set; }
            public DateTime? CreateDate { get; set; }
            public DateTime? Deadline { get; set; }
            public bool? Enable { get; set; }
        }
    }
}